﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_Customer_CustomerList : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            Utils.loadLocation(cboProvince, 0, 1, 0);
            Utils.loadLocation(cboDistrict, 0, 1, 2);

            Utils.loadLocation(cboProvinceCreate, 0, 1, 0);
            Utils.loadLocation(cboDistrictCreate, 0, 1, 2);

            gv.DataSource = new DataTable();
            gv.Height = 100;
            gv.DataBind();
        }
    }

    protected void cboProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        string provinceID = cboProvince.SelectedValue;
        Utils.loadLocation(cboDistrict, int.Parse(provinceID), 1, 0);
    }
    protected void cboProvinceCreate_SelectedIndexChanged(object sender, EventArgs e)
    {
        string provinceID = cboProvinceCreate.SelectedValue;
        Utils.loadLocation(cboDistrictCreate, int.Parse(provinceID), 1, 0);
    }
    protected void gvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        Loaddata();

    }
    private void Loaddata()
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();

        String CustomerCode = Utils.KillChars(this.txtCustomerCodeNew.Text.Trim());
        String CustomerName = Utils.KillChars(this.txtCustomerNameNew.Text.Trim());
        String CustomerPhone = Utils.KillChars(this.txtPhoneNumber.Text.Trim());
        int ProvinceID = int.Parse( this.cboProvince.SelectedValue);
        int DistrictID = int.Parse(this.cboDistrict.SelectedValue == "" ? "0" : this.cboDistrict.SelectedValue);
        int PageNumber = gv.CurrentPageIndex + 1;
        int PageSize = gv.PageSize;

        DateTime FromDate = new DateTime(2014, 06, 01);
        if (this.dtpFromDate.SelectedDate != null)
        {
            FromDate = this.dtpFromDate.SelectedDate.Value;
        }
        DateTime ToDate = new DateTime(2099, 12, 31);
        if (this.dtpToDate.SelectedDate != null)
        {
            ToDate = this.dtpToDate.SelectedDate.Value;
        }
        var q = db.Customer_Search(CustomerCode, CustomerName, CustomerPhone, "", ProvinceID, DistrictID,FromDate,ToDate, PageSize, PageNumber).ToList();
        if (q.Count > 0)
        {
            gv.ClientSettings.Scrolling.UseStaticHeaders = true;
            gv.VirtualItemCount = q[0].TotalRows.Value;
           
            gv.Height = 250;
            gv.ClientSettings.Scrolling.AllowScroll = true;
            gv.ClientSettings.Scrolling.UseStaticHeaders = true;
            gv.DataSource = q;
            
        }
        else
        {
            gv.DataSource = new DataTable();
        }
    }
    protected void btnCusSearch_Click(object sender, EventArgs e)
    {
        Loaddata();
        gv.DataBind();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            DBDataContext db = LINQUtil.GetDBWriteOnly();
            Customer cus = createCustomerObj(db);
            if (this.txtCustomerCodeCreate.Text != "")
            {
                if (txtPhoneNumberCreate.Text.Trim() != "")
                {
                    var checkCus = (from c in db.Customers
                                    where c.PhoneNumber.Trim() == txtPhoneNumberCreate.Text.Trim()
                                    && c.CustomerCode != this.txtCustomerCodeCreate.Text
                                    select c).FirstOrDefault();
                    if (checkCus != null)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số điện thoại: " + checkCus.PhoneNumber + " đã tồn tại");
                        return;
                    }
                }
                db.Update<Customer>(cus);
                db.SubmitChanges();
            }
            else
            {
                if (txtPhoneNumberCreate.Text.Trim() != "")
                {
                    var checkCus = (from c in db.Customers
                                    where c.PhoneNumber.Trim() == txtPhoneNumberCreate.Text.Trim()
                                    select c).FirstOrDefault();
                    if (checkCus != null)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số điện thoại: " + checkCus.PhoneNumber + " đã tồn tại");
                        return;
                    }
                }
                cus.CreatedBy = Session["UserName"].ToString();
                cus.CreatedDateTime = DateTime.Now;
                db.Insert<Customer>(cus);
                db.SubmitChanges();
            }
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công");
            this.txtCustomerCodeNew.Text = this.txtCustomerCodeCreate.Text;
            Loaddata();
            gv.DataBind();
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra");
            ControlUtil.LogError("----------------------------");
            ControlUtil.LogError("CustomerList-btnSave_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("----------------------------");
        }
    }
    protected void gvData_ItemCommand(object sender, GridCommandEventArgs e)
    {
        string commandName = e.CommandName;
        string cusID = e.CommandArgument.ToString();
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        if (commandName == "DelItem")
        {
            var cus = db.Customers.FirstOrDefault<Customer>(a=>a.ID == int.Parse(cusID));
            if (cus != null)
            {
                cus.Status = 'I';
                cus.LastUpdatedBy = Session["UserName"].ToString();
                cus.LastUpdatedDateTime = DateTime.Now;
                db.Update<Customer>(cus);
                db.SubmitChanges();
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công");
                Loaddata();
                gv.DataBind();
            }
        }
        else if (commandName == "EditItem")
        {
            var cus = db.Customers.FirstOrDefault<Customer>(a=>a.ID == int.Parse(cusID));
            if (cus != null)
            {
                this.txtCustomerNameCreate.Text = cus.CustomerName;
                this.txtCustomerCodeCreate.Text = cus.CustomerCode;
                this.txtPhoneNumberCreate.Text = cus.PhoneNumber;
                this.txtAddressCreate.Text = cus.Address;
                this.cboDistrictCreate.SelectedValue = cus.DistrictID.ToString();
                this.cboProvinceCreate.SelectedValue = cus.ProvinceID.ToString();
                TabStrip1.SelectedIndex = 1;
                RadPageView2.Selected = true;
            }
        }
    }

    private Customer createCustomerObj(DBDataContext db)
    {
        String CustomerName = Utils.KillChars(this.txtCustomerNameCreate.Text.Trim());
        String CustomerCode = Utils.KillChars(this.txtCustomerCodeCreate.Text.Trim());
        String CustomerPhone = Utils.KillChars(this.txtPhoneNumberCreate.Text.Trim());
        String Address = Utils.KillChars(this.txtAddressCreate.Text.Trim());
        int DistrictID = Convert.ToInt32(this.cboDistrictCreate.SelectedValue == "" ? "0" : this.cboDistrictCreate.SelectedValue);
        int ProvinceID = Convert.ToInt32(this.cboProvinceCreate.SelectedValue == "" ? "0" : this.cboProvinceCreate.SelectedValue);

        Customer customer = new Customer();

        var checkCus = (from cus in db.Customers
                        where cus.CustomerCode.Trim() == CustomerCode.Trim()
                        select cus).FirstOrDefault();
        if (checkCus != null)
        {
            customer = checkCus;
        }
        else
        {
            //Lay ma sau cung
            int lenZero = 7;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
            var customerCodeMax = db.Customers.Max(d => d.OrderNumber);
            int MaxOrderNumber = (customerCodeMax == null ? 0 : Convert.ToInt32(customerCodeMax)) + 1;
            String LastCode = ("000000" + MaxOrderNumber).ToString();
            CustomerCode = "KH" + LastCode.Substring(LastCode.Length - lenZero);
            customer.CustomerCode = CustomerCode;
            customer.AccumulateAmount = 0;
            customer.ConvertedAmount = 0;
            customer.RemainAmount = 0;
            //End
        }
        
        customer.CustomerName = CustomerName;
        customer.PhoneNumber = CustomerPhone.Trim();
        customer.Email = "";
        customer.Address = Address;
        customer.DistrictID = DistrictID;
        customer.ProvinceID = ProvinceID;

        //customer.CreatedBy = Session["UserName"].ToString();
        //customer.CreatedDateTime = DateTime.Now;
        customer.LastUpdatedBy = Session["UserName"].ToString();
        customer.LastUpdatedDateTime = DateTime.Now;
        customer.Status = 'A';

        return customer;
    }
}